<template>
  <div class="coupon-selector">
    <!-- 优惠券选择按钮 -->
    <div class="coupon-trigger" @click="showCouponDialog = true">
      <div class="coupon-info">
        <el-icon class="coupon-icon"><Ticket /></el-icon>
        <span class="coupon-text">
          {{ selectedCoupons.length > 0 ? `已选择${selectedCoupons.length}张优惠券` : '选择优惠券' }}
        </span>
      </div>
      <div class="coupon-discount" v-if="totalDiscount > 0">
        <span class="discount-text">-¥{{ totalDiscount.toFixed(2) }}</span>
      </div>
      <el-icon class="arrow-icon"><ArrowRight /></el-icon>
    </div>

    <!-- 优惠券选择对话框 -->
    <el-dialog
      v-model="showCouponDialog"
      title="选择优惠券"
      width="600px"
      @close="handleDialogClose"
    >
      <div class="coupon-dialog-content">
        <!-- 手动输入优惠券代码 -->
        <div class="coupon-input-section">
          <h4>输入优惠券代码</h4>
          <div class="input-group">
            <el-input
              v-model="couponCode"
              placeholder="请输入优惠券代码"
              @keyup.enter="addCouponByCode"
            />
            <el-button type="primary" @click="addCouponByCode" :loading="validating">
              添加
            </el-button>
          </div>
        </div>

        <!-- 可用优惠券列表 -->
        <div class="available-coupons-section">
          <h4>可用优惠券</h4>
          <div class="coupons-list" v-loading="loading">
            <div 
              v-for="coupon in availableCoupons" 
              :key="coupon.id"
              class="coupon-item"
              :class="{ 
                'selected': isSelected(coupon.id),
                'disabled': !canUseCoupon(coupon)
              }"
              @click="toggleCoupon(coupon)"
            >
              <div class="coupon-content">
                <div class="coupon-header">
                  <div class="coupon-value">
                    <span class="value-text">
                      {{ coupon.type === 'percentage' ? `${coupon.value}%` : `¥${coupon.value}` }}
                    </span>
                    <span class="value-label">
                      {{ coupon.type === 'percentage' ? '折扣' : '立减' }}
                    </span>
                  </div>
                  <div class="coupon-info">
                    <div class="coupon-name">{{ coupon.name }}</div>
                    <div class="coupon-condition">
                      满¥{{ coupon.min_amount }}可用
                      <span v-if="coupon.max_discount && coupon.type === 'percentage'">
                        (最高减¥{{ coupon.max_discount }})
                      </span>
                    </div>
                  </div>
                </div>
                
                <div class="coupon-footer">
                  <div class="coupon-validity">
                    有效期至：{{ formatDate(coupon.end_date) }}
                  </div>
                  <div class="coupon-usage" v-if="coupon.usage_limit">
                    剩余：{{ coupon.usage_limit - coupon.used_count }}张
                  </div>
                </div>
              </div>
              
              <div class="coupon-checkbox">
                <el-checkbox 
                  :model-value="isSelected(coupon.id)"
                  :disabled="!canUseCoupon(coupon)"
                />
              </div>
            </div>
          </div>
        </div>

        <!-- 已选择的优惠券 -->
        <div class="selected-coupons-section" v-if="selectedCoupons.length > 0">
          <h4>已选择的优惠券</h4>
          <div class="selected-coupons-list">
            <el-tag
              v-for="coupon in selectedCoupons"
              :key="coupon.id"
              closable
              @close="removeCoupon(coupon.id)"
              class="selected-coupon-tag"
            >
              {{ coupon.name }} 
              <span class="tag-discount">
                -¥{{ calculateSingleDiscount(coupon).toFixed(2) }}
              </span>
            </el-tag>
          </div>
        </div>

        <!-- 折扣预览 -->
        <div class="discount-preview" v-if="selectedCoupons.length > 0">
          <div class="preview-item">
            <span>原价：</span>
            <span>¥{{ safeOrderAmount.toFixed(2) }}</span>
          </div>
          <div class="preview-item discount">
            <span>优惠券折扣：</span>
            <span>-¥{{ totalDiscount.toFixed(2) }}</span>
          </div>
          <div class="preview-item final">
            <span>实付金额：</span>
            <span>¥{{ finalAmount.toFixed(2) }}</span>
          </div>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showCouponDialog = false">取消</el-button>
          <el-button type="primary" @click="confirmSelection">
            确定使用 ({{ selectedCoupons.length }}张)
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue';
import { ElMessage } from 'element-plus';
import { 
  getAvailableCouponsApi, 
  validateCouponApi,
  calculateCouponsDiscountApi 
} from '@/utils/api';
import { Ticket, ArrowRight } from '@element-plus/icons-vue';

// Props
const props = defineProps({
  orderAmount: {
    type: Number,
    required: true,
    default: 0
  },
  userId: {
    type: Number,
    required: true
  }
});

// 确保 orderAmount 始终是数字
const safeOrderAmount = computed(() => {
  return Number(props.orderAmount) || 0;
});

// Emits
const emit = defineEmits(['coupon-change']);

// 响应式数据
const showCouponDialog = ref(false);
const loading = ref(false);
const validating = ref(false);
const couponCode = ref('');
const availableCoupons = ref([]);
const selectedCoupons = ref([]);

// 计算属性
const totalDiscount = computed(() => {
  if (selectedCoupons.value.length === 0) return 0;

  let discount = 0;
  let remainingAmount = safeOrderAmount.value;

  for (const coupon of selectedCoupons.value) {
    const singleDiscount = calculateSingleDiscount(coupon, remainingAmount);
    discount += singleDiscount;
    remainingAmount -= singleDiscount;
  }

  return Math.min(discount, safeOrderAmount.value);
});

const finalAmount = computed(() => {
  return Math.max(0, safeOrderAmount.value - totalDiscount.value);
});

// 方法
const fetchAvailableCoupons = async () => {
  try {
    loading.value = true;
    const response = await getAvailableCouponsApi({ user_id: props.userId });
    if (response.code === 200) {
      availableCoupons.value = response.data || [];
    }
  } catch (error) {
    console.error('获取优惠券失败:', error);
    ElMessage.error('获取优惠券失败');
  } finally {
    loading.value = false;
  }
};

const addCouponByCode = async () => {
  if (!couponCode.value.trim()) {
    ElMessage.warning('请输入优惠券代码');
    return;
  }

  try {
    validating.value = true;
    const response = await validateCouponApi({
      code: couponCode.value,
      amount: safeOrderAmount.value,
      user_id: props.userId
    });

    if (response.code === 200) {
      const coupon = response.data.coupon;
      if (!isSelected(coupon.id)) {
        selectedCoupons.value.push(coupon);
        couponCode.value = '';
        ElMessage.success('优惠券添加成功');
      } else {
        ElMessage.warning('该优惠券已选择');
      }
    } else {
      ElMessage.error(response.message || '优惠券无效');
    }
  } catch (error) {
    console.error('验证优惠券失败:', error);
    ElMessage.error('验证优惠券失败');
  } finally {
    validating.value = false;
  }
};

const isSelected = (couponId) => {
  return selectedCoupons.value.some(c => c.id === couponId);
};

const canUseCoupon = (coupon) => {
  return safeOrderAmount.value >= coupon.min_amount;
};

const toggleCoupon = (coupon) => {
  if (!canUseCoupon(coupon)) {
    ElMessage.warning(`订单金额需满¥${coupon.min_amount}才能使用此优惠券`);
    return;
  }

  if (isSelected(coupon.id)) {
    removeCoupon(coupon.id);
  } else {
    selectedCoupons.value.push(coupon);
  }
};

const removeCoupon = (couponId) => {
  selectedCoupons.value = selectedCoupons.value.filter(c => c.id !== couponId);
};

const calculateSingleDiscount = (coupon, amount = null) => {
  const calcAmount = amount || safeOrderAmount.value;
  
  if (coupon.type === 'percentage') {
    let discount = (calcAmount * coupon.value) / 100;
    if (coupon.max_discount && discount > coupon.max_discount) {
      discount = coupon.max_discount;
    }
    return discount;
  } else if (coupon.type === 'fixed') {
    return Math.min(coupon.value, calcAmount);
  }
  return 0;
};

const confirmSelection = () => {
  showCouponDialog.value = false;
  emit('coupon-change', {
    coupons: selectedCoupons.value,
    totalDiscount: totalDiscount.value,
    finalAmount: finalAmount.value,
    couponCodes: selectedCoupons.value.map(c => c.code)
  });
};

const handleDialogClose = () => {
  // 对话框关闭时不重置选择，保持用户的选择状态
};

const formatDate = (dateStr) => {
  return new Date(dateStr).toLocaleDateString('zh-CN');
};

// 监听订单金额变化，重新计算可用优惠券
watch(() => safeOrderAmount.value, () => {
  // 移除不满足条件的优惠券
  selectedCoupons.value = selectedCoupons.value.filter(coupon =>
    canUseCoupon(coupon)
  );
});

// 监听选择变化，通知父组件
watch([selectedCoupons, totalDiscount], () => {
  emit('coupon-change', {
    coupons: selectedCoupons.value,
    totalDiscount: totalDiscount.value,
    finalAmount: finalAmount.value,
    couponCodes: selectedCoupons.value.map(c => c.code)
  });
}, { deep: true });

// 组件挂载时获取可用优惠券
onMounted(() => {
  fetchAvailableCoupons();
});

// 暴露方法给父组件
defineExpose({
  clearSelection: () => {
    selectedCoupons.value = [];
  },
  refreshCoupons: fetchAvailableCoupons
});
</script>

<style lang="less" scoped>
.coupon-selector {
  .coupon-trigger {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 12px 16px;
    background: #fff;
    border: 1px solid #e4e7ed;
    border-radius: 8px;
    cursor: pointer;
    transition: all 0.3s ease;

    &:hover {
      border-color: #409eff;
      background: #f5f7fa;
    }

    .coupon-info {
      display: flex;
      align-items: center;
      gap: 8px;

      .coupon-icon {
        color: #f56c6c;
        font-size: 18px;
      }

      .coupon-text {
        font-size: 14px;
        color: #606266;
      }
    }

    .coupon-discount {
      .discount-text {
        color: #f56c6c;
        font-weight: 600;
        font-size: 14px;
      }
    }

    .arrow-icon {
      color: #c0c4cc;
      font-size: 14px;
    }
  }
}

.coupon-dialog-content {
  .coupon-input-section {
    margin-bottom: 24px;

    h4 {
      margin: 0 0 12px 0;
      font-size: 16px;
      color: #303133;
    }

    .input-group {
      display: flex;
      gap: 12px;

      .el-input {
        flex: 1;
      }
    }
  }

  .available-coupons-section {
    margin-bottom: 24px;

    h4 {
      margin: 0 0 12px 0;
      font-size: 16px;
      color: #303133;
    }

    .coupons-list {
      max-height: 300px;
      overflow-y: auto;

      .coupon-item {
        display: flex;
        align-items: center;
        padding: 16px;
        margin-bottom: 12px;
        border: 1px solid #e4e7ed;
        border-radius: 8px;
        cursor: pointer;
        transition: all 0.3s ease;

        &:hover:not(.disabled) {
          border-color: #409eff;
          box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
        }

        &.selected {
          border-color: #409eff;
          background: #f0f9ff;
        }

        &.disabled {
          opacity: 0.5;
          cursor: not-allowed;
          background: #f5f7fa;
        }

        .coupon-content {
          flex: 1;

          .coupon-header {
            display: flex;
            align-items: center;
            gap: 16px;
            margin-bottom: 8px;

            .coupon-value {
              display: flex;
              flex-direction: column;
              align-items: center;
              min-width: 80px;

              .value-text {
                font-size: 20px;
                font-weight: 600;
                color: #f56c6c;
              }

              .value-label {
                font-size: 12px;
                color: #909399;
              }
            }

            .coupon-info {
              flex: 1;

              .coupon-name {
                font-size: 16px;
                font-weight: 500;
                color: #303133;
                margin-bottom: 4px;
              }

              .coupon-condition {
                font-size: 12px;
                color: #909399;
              }
            }
          }

          .coupon-footer {
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-size: 12px;
            color: #909399;
          }
        }

        .coupon-checkbox {
          margin-left: 12px;
        }
      }
    }
  }

  .selected-coupons-section {
    margin-bottom: 24px;

    h4 {
      margin: 0 0 12px 0;
      font-size: 16px;
      color: #303133;
    }

    .selected-coupons-list {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;

      .selected-coupon-tag {
        .tag-discount {
          margin-left: 4px;
          color: #f56c6c;
          font-weight: 600;
        }
      }
    }
  }

  .discount-preview {
    padding: 16px;
    background: #f5f7fa;
    border-radius: 8px;
    border: 1px solid #e4e7ed;

    .preview-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 8px;
      font-size: 14px;

      &:last-child {
        margin-bottom: 0;
      }

      &.discount {
        color: #f56c6c;
      }

      &.final {
        font-size: 16px;
        font-weight: 600;
        color: #303133;
        padding-top: 8px;
        border-top: 1px solid #e4e7ed;
      }
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

// 响应式设计
@media (max-width: 768px) {
  .coupon-dialog-content {
    .coupon-item {
      .coupon-header {
        flex-direction: column;
        align-items: flex-start;
        gap: 8px;

        .coupon-value {
          align-self: flex-start;
          min-width: auto;
        }
      }
    }

    .input-group {
      flex-direction: column;

      .el-input {
        margin-bottom: 12px;
      }
    }
  }
}
</style>
